#include <stdio.h>
#include <deque>
using namespace std;

int n, m;
char cave[12][12];
deque< pair< pair<int, int> , int> > q;

void checkRoom() {
	int y=q.front().first.first, x=q.front().first.second;
	int numRooms = q.front().second;

	if (x+1<m) {
		if (cave[y][x+1]!='V' && cave[y][x+1]!='2')
			q.push_back(make_pair(make_pair(y, x+1), numRooms+1)); 
	}
	
	if (x-1>=0) {
		if (cave[y][x-1]!='V' && cave[y][x-1]!='2')
			q.push_back(make_pair(make_pair(y, x-1), numRooms+1)); 
	}
	
	if (y+1<n) {
		if (cave[y+1][x]!='V' && cave[y+1][x]!='2')
			q.push_back(make_pair(make_pair(y+1, x), numRooms+1));
	}
	
	if (y-1>=0) {
		if (cave[y-1][x]!='V' && cave[y-1][x]!='2')
			q.push_back(make_pair(make_pair(y-1, x), numRooms+1));
	}

	cave[y][x]='V';
} 

void BSF() {
	int initI, initJ;

	for (int i=0; i<n; i++) {
		for (int j=0; j<m; j++)
			if (cave[i][j]=='3') {
				initI=i;
				initJ=j;
			}
	}

	q.push_back(make_pair(make_pair(initI, initJ), 0));

	while (cave[q.front().first.first][q.front().first.second]!='0') {
		checkRoom();
		q.pop_front();
	}
}

int main() {
	scanf("%d %d", &n, &m);
	
	for (int i=0; i<n; i++) {
		for (int j=0; j<m; j++)
			scanf(" %c", &cave[i][j]);
	}

	BSF();	

	printf("%d\n", q.front().second);

	return 0;
}
